<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keywords" placeholder="关键词"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="add">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="batchShelf">批量上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="batchOffShelf">批量下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table border :data="tableData" height="430" highlight-current-row v-loading="listLoading"
              @selection-change="selectChange"
              style="width: 100%;">
      <el-table-column type="selection" fixed>
      </el-table-column>
      <el-table-column prop="title" label="标题" fixed>
      </el-table-column>
      <el-table-column prop="cover" label="封面" fixed width="120">
        <template slot-scope="scope">
          <img :src="FILE_SERVER + scope.row.cover"
               width="100"
               style="height: auto; max-width: 100px;"
               alt="无法显示"/>
        </template>
      </el-table-column>
      <el-table-column prop="salePrice" label="原价">
      </el-table-column>
      <el-table-column prop="costPrice" label="售价">
      </el-table-column>
      <el-table-column prop="isNew" label="是否新车">
        <template slot-scope="scope">
          <!--1 是 0 否 用el-tag-->
          <el-tag v-if="scope.row.isNew === 1" type="success">是</el-tag>
          <el-tag v-if="scope.row.isNew === 0" type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="registerTime" label="上牌时间" width="95">
      </el-table-column>
      <el-table-column prop="mileage" label="里程">
      </el-table-column>
      <el-table-column prop="shopName" label="店铺名称">
      </el-table-column>
      <el-table-column prop="onSaleTime" label="上架时间" width="150">
      </el-table-column>
      <el-table-column prop="offSaleTime" label="下架时间" width="150">
      </el-table-column>
      <el-table-column prop="state" label="状态">
        <template slot-scope="scope">
          <!--1 上架 0 下架-- 用el-tag-->
          <el-tag v-if="scope.row.state === 1" type="success">上架</el-tag>
          <el-tag v-if="scope.row.state === 0" type="danger">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="costEffective" label="超值">
        <template slot-scope="scope">
          <!--1 超值 0 不超值 用el-tag-->
          <el-tag v-if="scope.row.costEffective === 1" type="success">是</el-tag>
          <el-tag v-if="scope.row.costEffective === 0" type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="rushSale" label="急售">
        <template slot-scope="scope">
          <!--1 是 0 否 用el-tag-->
          <el-tag v-if="scope.row.rushSale === 1" type="success">是</el-tag>
          <el-tag v-if="scope.row.rushSale === 0" type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="quasiNewCar" label="准新车">
        <template slot-scope="scope">
          <!--1 是 0 否 用el-tag-->
          <el-tag v-if="scope.row.quasiNewCar === 1" type="success">是</el-tag>
          <el-tag v-if="scope.row.quasiNewCar === 0" type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="transitiveCountry" label="可迁全国">
        <template slot-scope="scope">
          <!--1 是 0 否 用el-tag-->
          <el-tag v-if="scope.row.transitiveCountry === 1" type="success">是</el-tag>
          <el-tag v-if="scope.row.transitiveCountry === 0" type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="carType.name" label="类型">
      </el-table-column>
      <el-table-column prop="seller.username" label="销售顾问">
      </el-table-column>
      <el-table-column prop="auditState" label="审核状态">
        <template slot-scope="scope">
          <!--1 通过 0 驳回 用el-tag-->
          <el-tag v-if="scope.row.auditState === 1" type="success">通过</el-tag>
          <el-tag v-if="scope.row.auditState === -1" type="danger">驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="146">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="194">
        <template slot-scope="scope">
          <el-button size="mini" @click="resourceMaintenance(scope.row)">资源维护</el-button>
          <el-button type="primary" size="mini" @click="uploadQuality(scope.$index, scope.row)">上传质检</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="70">
        <template slot-scope="scope">
          <el-button size="mini" :type="scope.row.state === 0 ? 'success' : 'danger'"
                     @click="onOrOffSale(scope.row)">
            {{ scope.row.state === 1 ? '下架' : '上架' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.selection.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>
    <el-dialog :title="title" :visible.sync="dialogVisible" @close="dialogClose" width="50%">
      <el-form :model="car" label-width="80px" ref="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="car.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/file/upload"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="原价">
          <el-input v-model="car.salePrice" style="width:220px;" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价">
          <el-input v-model="car.costPrice" style="width:220px;" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否新车">
          <el-radio-group v-model="car.isNew">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上牌时间">
          <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="car.registerTime"
              type="date"
              placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="里程数">
          <el-input v-model="car.mileage" style="width:220px;" type="number" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="超值">
          <el-radio-group v-model="car.costEffective">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="急售">
          <el-radio-group v-model="car.rushSale">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="准新车">
          <el-radio-group v-model="car.quasiNewCar">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可迁全国">
          <el-radio-group v-model="car.transitiveCountry">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="车辆类型">
          <el-cascader v-model="car.typeId"
                       :options="carTypeTree"
                       :props="{
							            checkStrictly: true,
							            label:'name',
							            value:'id'
							         }" clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="基本信息">
          <quill-editor v-model="car.carDetail.info"
                        :options="editorOption">
          </quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogClose">取消</el-button>
          <el-button type="primary" @click="submit" :loading="saveLoading">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="资源维护" :visible.sync="carResourceVisible" @close="carResourceClose" :close-on-click-modal="false">
      <el-form label-width="80px" ref="carResourceForm">
        <el-form-item label="主图">
          <!--file-list 可以用来做图片回显的-->
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/file/upload"
              :on-remove="imgHandleRemove"
              :on-success="imgHandleSuccess"
              :file-list="imgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="副图">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/file/upload"
              :on-remove="viceimgHandleRemove"
              :on-success="viceimgHandleSuccess"
              :file-list="viceimgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="更多图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/file/upload"
              :on-remove="moreimgHandleRemove"
              :on-success="moreimgHandleSuccess"
              :file-list="moreimgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="carResourceVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveCarResource" :loading="addLoading2">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import {quillEditor} from "vue-quill-editor"; // 在页面中引入富文本编辑框的组件
import 'quill/dist/quill.core.css';   // 引入样式
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from "../../common/js/quill-config";

export default {
  components: {
    quillEditor   // 如果key和value的名字一样,可以省略 quillEditor:quillEditor
  },
  name: "Car",
  data() {
    return {
      editorOption: quillConfig,
      query: {
        keywords: ''
      },
      currentPage: 1,
      pageSize: 5,
      total: 0,
      tableData: [],
      fileList: [],
      imgFileList: [],
      viceimgFileList: [],
      moreimgFileList: [],
      addLoading2: false,
      listLoading: false,
      selection: [],
      dialogVisible: false,
      title: '',
      token: {
        "TOKEN": localStorage.getItem('token')
      },
      car: {
        carDetail: {
          info: ''
        },
      },
      carResourceVisible: false,
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'}
        ]
      },
      saveLoading: false,
      deptList: [],
      carTypeTree: [],
      carResources: [],
      carId: null,
    }
  },
  mounted() {
    this.getCarList();
  },
  methods: {
    batchShelf() {
      if (this.selection.length === 0) {
        this.$message.error('请选择要上架的商品')
        return;
      }
      this.$confirm('确定要上架选中的商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.batchOnOrOffSale(1)
      });
    },
    batchOffShelf() {
      if (this.selection.length === 0) {
        this.$message.error('请选择要下架的商品')
        return;
      }
      this.$confirm('确定要下架选中的商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.batchOnOrOffSale(0)
      });
    },
    onOrOffSale(row) {
      let stateParam = row.state === 1 ? 0 : 1;
      let tip = stateParam === 1 ? '上架' : '下架';
      this.$confirm(`确定要${tip}该商品吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 将id添加到selection数组中
        this.selection.push(row.id);
        this.batchOnOrOffSale(stateParam)
      });
    },
    batchOnOrOffSale(stateParam) {
      this.$axios.post("/car/" + (stateParam === 1 ? "onSale" : "offSale"), this.selection).then(res => {
        if (res.data.code === 1) {
          this.$message({
            message: res.data.data || '操作成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
        this.selection = [];
        this.getCarList();
      })
    },
    carResourceClose() {
      this.carResources = [];
      this.imgFileList = [];
      this.viceimgFileList = [];
      this.moreimgFileList = [];
      this.carResourceVisible = false;
    },
    saveCarResource() {
      if (this.carResources.length === 0) {
        this.$message.error('请上传图片');
        this.addLoading2 = false;
      } else {
        this.addLoading2 = true;
        this.$axios.post("/carResources/batchAdd", this.carResources)
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  message: '保存成功!',
                  type: 'success'
                });
                this.carResourceClose()
              } else {
                this.$message({
                  message: '保存失败!',
                  type: 'error'
                });
              }
              this.addLoading2 = false;
            })
      }
    },
    resourceMaintenance(row) {
      this.carResourceVisible = true;
      this.carId = row.id;
      this.getResources(row.id);
    },
    getResources(id) {
      this.$axios.get("/carResources/carId/" + id)
          .then(res => {
            if (res.data.code === 1) {
              this.carResources = res.data.data;
              // 遍历carResources,判断图片类型,然后分别赋值给imgFileList,viceimgFileList,moreimgFileList
              this.carResources.forEach(item => {
                if (item.type === 1) {
                  this.imgFileList.push({
                    carId: id,
                    type: 1,
                    url: this.FILE_SERVER + item.url,
                    response: {data: item.url}
                  })
                } else if (item.type === 2) {
                  this.viceimgFileList.push({
                    carId: id,
                    type: 2,
                    url: this.FILE_SERVER + item.url,
                    response: {data: item.url}
                  })
                } else if (item.type === 3) {
                  this.moreimgFileList.push({
                    carId: id,
                    type: 3,
                    url: this.FILE_SERVER + item.url,
                    response: {data: item.url}
                  })
                }
              })
            } else {
              this.$message.error(res.data.msg || '获取失败');
            }
          })
    },
    //文件删除
    handleRemove(file, fileList) {
      let filePath = file.response.data;
      this.deleteImage(filePath);
    },
    deleteImage(filePath) {
      this.$axios.delete("/file/delete/?path=" + filePath)
          .then(res => {
            if (res.data.code === 1) {
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
              this.car.cover = "";
            } else {
              this.$message({
                message: '删除失败!',
                type: 'error'
              });
            }
          })
    },
    removeItem(filePath) {
      // 移除carResources数组中的指定元素
      for (let i = 0; i < this.carResources.length; i++) {
        if (this.carResources[i].url === filePath) {
          this.carResources.splice(i, 1);
          break;
        }
      }
    },
    imgHandleRemove(file, fileList) {
      let filePath = file.response.data;
      this.deleteImage(filePath);
      // 移除carResources数组中的指定元素
      this.removeItem(filePath)
    },
    imgHandleSuccess(response, file, fileList) {
      // 向carResources数组中插入数据
      this.carResources.push({
        carId: this.carId,
        type: 1,
        url: response.data
      });
    },
    viceimgHandleRemove(file, fileList) {
      let filePath = file.response.data;
      this.deleteImage(filePath);
      // 移除carResources数组中的指定元素
      this.removeItem(filePath)
    },
    viceimgHandleSuccess(response, file, fileList) {
      // 向carResources数组中插入数据
      this.carResources.push({
        carId: this.carId,
        type: 2,
        url: response.data
      });
    },
    moreimgHandleRemove(file, fileList) {
      let filePath = file.response.data;
      this.deleteImage(filePath)
      // 移除carResources数组中的指定元素
      this.removeItem(filePath)
    },
    moreimgHandleSuccess(response, file, fileList) {
      // 向carResources数组中插入数据
      this.carResources.push({
        carId: this.carId,
        type: 3,
        url: response.data
      });
    },
    //文件上传成功回调
    handleSuccess(response, file, fileList) {
      this.car.cover = response.data;
    },
    batchRemove() {
      this.$axios.patch('/car', this.selection)
          .then(res => {
            if (res.data.code === 1) {
              this.$message.success("删除成功!");
              this.getCarList();
            } else {
              this.$message.error(res.data.msg || '删除失败');
            }
          })
    },
    search() {
      this.currentPage = 1;
      this.getCarList();
    },
    getCarList() {
      this.$axios.post('/car', {
        keywords: this.query.keywords,
        page: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        if (res.data.code === 1) {
          this.tableData = res.data.data.rows;
          this.total = res.data.data.total;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    add() {
      this.getTreeData();
      this.title = '新增车辆';
      this.dialogVisible = true;
    },
    getTreeData() {
      // 发送一个异步请求: get请求 /product/carType/treeData
      this.$axios.get("/carType/tree").then(res => {
        if (res.data.code === 1) {
          this.carTypeTree = res.data.data;
        } else {
          this.$message.error(res.data.msg)
        }
      });
    },
    submit() {
      this.$refs.rules.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {type: 'warning'}).then(() => {
            this.saveLoading = true;
            // 如果this.car.typeId是一个数组，则this.car.typeId = this.car.typeId[this.car.typeId.length - 1];
            if (this.car.typeId instanceof Array) {
              this.car.typeId = this.car.typeId[this.car.typeId.length - 1];
            }
            this.$axios.put('/car', this.car).then((res) => {
              this.saveLoading = false;
              if (res.data.code === 1) {
                this.$message.success("提交成功")
                this.car = {
                  carDetail: {
                    info: ''
                  },
                };
              } else {
                this.$message.error(res.data.msg || '提交失败');
              }
              this.$refs['rules'].resetFields();
              this.dialogVisible = false;
              this.getCarList();
            });
          });
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getCarList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getCarList();
    },
    selectChange(val) {
      this.selection = val.map(item => item.id);
    },
    dialogClose() {
      // 重置表单
      this.car = {
        carDetail: {
          info: ''
        },
      };
      this.dialogVisible = false;
      // 清空文件列表
      this.fileList = [];
    },
    handleEdit(row) {
      this.getTreeData();
      this.title = '编辑车辆';
      this.dialogVisible = true;
      this.car = {...row};
      this.fileList = [{name: row.cover, response: {data: row.cover}, url: this.FILE_SERVER + row.cover}];
    },
    handleDel(id) {
      this.$confirm('确认删除该车辆吗？', '提示', {type: 'warning'}).then(() => {
        this.listLoading = true;
        this.$axios.delete('/car/' + id).then((res) => {
          this.listLoading = false;
          if (res.data.code === 1) {
            this.$message.success("删除成功")
            //如果当前页数据被删除完了，则自动切换到上一页
            if (this.tableData.length === 1 && this.currentPage > 1) {
              this.currentPage--;
            }
            this.getCarList();
          } else {
            this.$message.error(res.data.msg || '删除失败');
          }
        })
      })
    }
  }
}
</script>

<style scoped>

</style>